package com.cetc.nsfx.util;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;


public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter {
	private String[] allowUrls;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
	    request.setCharacterEncoding("UTF-8");  
		response.setCharacterEncoding("UTF-8");  
		response.setContentType("text/html;charset=UTF-8");  
		String requestUrl = request.getRequestURI();
		String ctx = request.getContextPath();
//		SysUser user = (SysUser) WebUtils.getSessionAttribute(request, "userInfo");
		Object user=null;
		PrintWriter out = response.getWriter();
		StringBuilder builder = new StringBuilder();
		if (user != null) {
			if(requestUrl.endsWith(ctx)||requestUrl.endsWith(ctx+"/")){
				builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
				builder.append("window.top.location.href=\"");
				builder.append(ctx);
				builder.append("/main\";</script>");
				out.print(builder.toString());
				out.close();
				return true;
			}else{
				return true;
			}

		} else if(user==null){
			//过滤掉不需要验证的url
			for (String url : allowUrls) {
				if (requestUrl.endsWith(url)) {
					return true;
				}
			}
			// 未登录
			
			builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
			builder.append("alert(\"页面过期，请重新登录\");");
			builder.append("window.top.location.href=\"");
			builder.append(ctx);
			builder.append("/index\";</script>");
			out.print(builder.toString());
			out.close();
			return false;

		}else{
			throw new RuntimeException();
		}
	}

	public String[] getAllowUrls() {
		return allowUrls;
	}

	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}

}
